package likou.jindian;

/**
 * @author: Tangxz
 * @email: 1171702529@qq.com
 * @cate: 2020/11/25 12:07
 */
class StackOfPlates {
    int[][] stacks;
    int max;
    int cur;

    public StackOfPlates(int cap) {
        this.max = cap;
        // 第0个位置存放元素个数
        this.stacks = new int[1][max+1];
        this.cur = 0;
    }

    public void push(int val) {
        if(max <= 0) return;
        // 扩容
        if(stacks[cur][0] == max){
            int[][] tmp = new int[cur+2][max+1];
            //复制元素
            for(int i = 0; i <= cur; i++){
                tmp[i] = stacks[i];
            }
            this.stacks = tmp;
            cur++;
        }
        stacks[cur][0]++;
        stacks[cur][stacks[cur][0]] = val;
    }

    public int pop() {
        // 为空
        if(cur == 0 && stacks[cur][0] == 0) return -1;
        int res = stacks[cur][stacks[cur][0]];
        stacks[cur][0]--;
        removeStackIfEmpty(cur);
        return res;
    }

    public int popAt(int index) {
        if(index > cur || index < 0 || stacks[index][0] == 0) return -1;
        int res = stacks[index][stacks[index][0]];
        stacks[index][0]--;
        removeStackIfEmpty(index);
        return res;
    }

    private void removeStackIfEmpty(int index){
        if(cur == 0) return;
        if(stacks[index][0] == 0){
            for(int i = index; i < cur; i++){
                stacks[i] = stacks[i+1];
            }
            cur--;
        }
    }
}